var express = require('express');
var router = express.Router();
var EventProxy = require('eventproxy');
var util = require('util');

var logger = require("../models/logger")
var Event = require("../models/Event");
var resultJson = require("../result-json");
var Utils = require("../utils");
var Consts = require("../consts");
var User = require("../models/User");

router.post('/', function(req, res) {
    res.send('respond with a resource');
});

/**
 * 根据id查询详情
 */
router.post("/detail", function(req, res) {
    var event = req.body;
    Event.findById(event._id, function(err, event) {
        if (err ) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        if (!event)
            return res.send(resultJson(200));
        
        event = JSON.parse(JSON.stringify(event));
        User.findOne({
            "_id": event.from
        }, function(err, user) {
            if (err || !user)
                return res.send(resultJson(3));

            event.user = user;
            res.send(resultJson(0, event));
        });
    });
});


/**
 * 根据from查询详情
 */
router.post("/user", function(req, res) {
    var events = req.body;
    var from=events.from;
    Event.findById(from, function(err, event) {
        if (err ) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        // if (!event)
            // return res.send(resultJson(200));
//         
        // event = JSON.parse(JSON.stringify(event));
        User.findOne({
            "_id": from
        }, function(err, user) {
            if (err || !user)
                return res.send(resultJson(3));
            res.send(resultJson(0, user));
        });
    });
});



/**根据手机号和姓名查询用户*/
router.post('/cont', function(req, res) {
    var event=req.body;
    console.log("ph:"+event.phone);
    console.log("nm:"+event.name);
    // var ph = req.body.ph;
    // var nm = req.body.nm;
    User.findOne({
        ph:event.phone,
        nm:event.name
    }).exec(function(err, user) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        user = JSON.parse(JSON.stringify(user));
        res.send(resultJson(0,user));
        console.log("user:"+user);
    });
});


/**
 * 根据id查询详情
 */
router.post("/listname", function(req, res) {
    var event = req.body;
    var eid=event._id;
    var arr = new Array();
    Event.findById(eid, function(err, event) {
        if (err ) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        var length = event.users.length || 0;
        if(length==0){
           return res.send(resultJson(0,arr)); 
        }
        var count=0;
        for(var i=0; i<length; i++) {
            User.findOne({
            _id: event.users[i].id
            }, function(err, user) {
                if (err || !user)
                    return res.send(resultJson(3));
                ++count;
                arr.push(user);
                if(count == length){
                    res.send(resultJson(0,arr));
                }
            });
        }
        
        
    });
});

//增加新活动或修改活动
router.post('/upsert', function(req, res) {
    var event = req.body;
    event.create = new Date();
    if (event._id) {
        var _id = event._id;
        delete event._id;
        Event.update({
            _id: _id
        }, {
            $set: event
        }).exec(function(err) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            res.send(resultJson(0));
        });
    } else {
        event.from = event._user._id;
        new Event(event).save(function(err, event) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            res.send(resultJson(0, event));
        });
    }
});



router.post('/upsert1', function(req, res) {
    var event = req.body;
    var _id = event._id;
    event.create = new Date();
    if (event._id) {
        delete event._id;
        Event.update({
            _id:_id
        }, {
            $set: event
        }, function(err) {
            console.log(err);
            if (err)
                return res.send(resultJson(2));
            return res.send(resultJson(0));
        });
    } else {
       return res.send(resultJson(0, event));
     }
});


//列出所有参加活动，如果带id参数，那么列出该人下所有活动
router.post('/attendList', function(req, res) {
    list(req, res);
});

//列出所有举办活动，如果带id参数，那么列出该人下所有活动
router.post('/myList', function(req, res) {
    list(req, res);
});

//列出所有活动，如果带id参数，那么列出该人下所有活动
router.post('/list', function(req, res) {
    list(req, res);
});

router.post('/bj', function(req, res) {
    list(req, res);
});
router.post('/sh', function(req, res) {
    list(req, res);
});
router.post('/gz', function(req, res) {
    list(req, res);
});
router.post('/sz', function(req, res) {
    list(req, res);
});
router.post('/qt', function(req, res) {
    list(req, res);
});


function list(req, res) {
    var event = req.body;
    var start = event.start || 0;
    var count = event.count || Consts.MAX;
    var option = {};
    if (event.from)
        option.from = event.from;
    if (event.category)
        option.category = event.category;
    if (event.address)
        option.address = event.address;


    Event.find(option).skip(start).limit(count).sort({
        create: -1
    }).exec(function(err, events) {
        if (err) {
            logger.error(err);
            return res.send(resultJson(2));
        }

        var results;
        if(!event.category) {
            results = [];
            var length = events && events.length || 0;
            for(var i=0; i<length; i++) {
                if(events[i].category != Consts.EVENTTYPE.TYPE_JOB)
                    results.push(events[i]);
            }
        }else
            results = events;

        if(event.user) {
            for(var i=results.length-1; i>=0; i--) {
                var find = false;
                var length = results[i].users && results[i].users.length || 0;
                for(var j=0; j<length; j++) {
                    if(results[i].users[j].id == event.user) {
                        find = true;
                        break;
                    }
                }
                if(find == false)
                    results.splice(i, 1);
            }
        }

        results = JSON.parse(JSON.stringify(results));
        fromName(res, 0, results);
    });    
};

function fromName(res, index, events) {
    if (index == events.length || events.length == 0) {
        return res.send(resultJson(0, {
            "count": events.length,
            "results": events
        }));
    } else {
        User.findOne({
            "_id": events[index].from
        }, function(err, user) {
            if (err) {
                logger.error(err);
                return res.send(resultJson(2));
            }
            if (!user)
                user = {};

            events[index].fromName = user.name;
            index++;
            fromName(res, index, events);
        });
    }
};


//退出活动
router.post('/quitevent', function(req, res) {
    var event = req.body;
    //var _id=event.cid;
    var uid=event.uid;
    var _id=event.qev._id;
    //1  拿_id去查活动
    Event.findById(_id, function(err, users) {
        if (err ) {
            logger.error(err);
            return res.send(resultJson(2));
        }
        //2  拿到参见活动的人。.users
        console.log(users);
        //3  从users里删除uid
        //4 update  条件是_id   数据  
        Event.update({
            _id: _id,
            "users.id" : uid
            }, {
                $pull: {
                    users: {
                       "users.id": _id
                    },
                },
            }, function(err) {
                if (err)
                    return res.send(resultJson(2));
            });
        res.send(resultJson(0,users));
    });
});

//删除
router.post('/remove', function(req, res) {
    var event = req.body;
    Event.remove({
        _id: event._id
    }, function(err) {
        if (err) {
            logger.error(err);
            res.send(resultJson(2));
        } else
            res.send(resultJson(0));
    });
});

module.exports = router;